package cn.wolfcode.wolf2w.service.impl;

import cn.wolfcode.wolf2w.domain.Destination;
import cn.wolfcode.wolf2w.domain.Strategy;
import cn.wolfcode.wolf2w.domain.StrategyCatalog;
import cn.wolfcode.wolf2w.domain.StrategyTheme;
import cn.wolfcode.wolf2w.exception.LogicalException;
import cn.wolfcode.wolf2w.query.StrategyQueryObject;
import cn.wolfcode.wolf2w.repository.StrategyRepository;
import cn.wolfcode.wolf2w.service.IDestinationService;
import cn.wolfcode.wolf2w.service.IStrategyCatalogService;
import cn.wolfcode.wolf2w.service.IStrategyService;
import cn.wolfcode.wolf2w.service.IStrategyThemeService;
import cn.wolfcode.wolf2w.util.PagingUtil;
import cn.wolfcode.wolf2w.vo.StrategyStatisVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;

@Service
//@Transactional
public class StrategyServiceImpl implements IStrategyService {

    @Autowired
    private StrategyRepository repository;

    @Autowired
    private MongoTemplate template;

    @Autowired
    private IStrategyCatalogService strategyCatalogService;

    @Autowired
    private IStrategyThemeService strategyThemeService;

    @Autowired
    private IDestinationService destinationService;


    @Override
    public void save(Strategy strategy) {
        strategy.setId(null);   //设为空值,防止数据库不会自动创建id
        repository.save(strategy);
    }

    @Override
    public void delete(String id) {
        repository.deleteById(id);

    }

    @Override
    public void update(Strategy strategy) {
        repository.save(strategy);
    }

    @Override
    public Strategy get(String id) {
        return repository.findById(id).orElse(null);
    }

    @Override
    public List<Strategy> list() {
        return repository.findAll();
    }

    @Override
    public Page<Strategy> query(StrategyQueryObject qo) {

        //查询封装类
        Query query = new Query();

        //查询分页
         Pageable pageable = PageRequest.of(qo.getCurrentPage()-1, qo.getPageSize(), Sort.Direction.ASC, "_id");

        //调用工具方法,返回分页数据
        return PagingUtil.query(query, template, Strategy.class, pageable);

    }

    @Override
    public void saveOrUpdate(Strategy strategy) {
        //前端缺少的字段
        //destId和destName
        String catalogId = strategy.getCatalogId();
        StrategyCatalog strategyCatalog = strategyCatalogService.get(catalogId);
        //将destId 和destName 设进对象
        strategy.setDestId(strategyCatalog.getDestId());
        strategy.setDestName(strategyCatalog.getDestName());
        //将catalogName设进对象
        strategy.setCatalogName(strategyCatalog.getName());
        //themeName
        StrategyTheme strategyTheme = strategyThemeService.get(strategy.getThemeId());
        strategy.setThemeName(strategyTheme.getName());
        //isabroad
        //获取所有的父级
        List<Destination> list = destinationService.checkParent(strategyCatalog.getDestId());
        //判断list是否有值
        if (list != null && list.size() >0){
            //如果第一个是中国就是国内
            /*if ("中国".equals(list.get(0).getName())){
                strategy.setIsabroad(Strategy.ABROAD_NO);
            }else {
                strategy.setIsabroad(Strategy.ABROAD_YES);
            }*/
            //三元判断
            strategy.setIsabroad("中国".equals(list.get(0).getName())? Strategy.ABROAD_NO : Strategy.ABROAD_YES);
        }

        //判断是否有id
        if (StringUtils.hasLength(strategy.getId())){
            //查询和替换
            Strategy str = this.get(strategy.getId());
            strategy.setCreateTime(str.getCreateTime());
            strategy.setReplynum(str.getReplynum());
            strategy.setFavornum(str.getFavornum());
            strategy.setThumbsupnum(str.getThumbsupnum());
            strategy.setSharenum(str.getSharenum());
            strategy.setViewnum(str.getViewnum());
            //这里是全量更新
            this.update(strategy);
        }else {
            //createTime
            strategy.setCreateTime(new Date());
            this.save(strategy);
        }
    }

    @Override
    public List<Strategy> findByCatalogId(String catalogId,Pageable pageable) {

        List<Strategy> strategies = repository.findByCatalogId(catalogId,pageable);
        return strategies;
    }

    @Override
    public List<Strategy> queryStrategies(String destId) {

        Pageable pageable = PageRequest.of(0, 3, Sort.Direction.DESC,"viewnum");

        List<Strategy> strategies = repository.findByDestId(destId,pageable);

        return strategies;
    }

    @Override
    public Page queryStrategiesBydestId(StrategyQueryObject qo) {

        Query query = new Query();

        //上级id
        if (StringUtils.hasLength(qo.getDestId())){
            query.addCriteria(Criteria.where("destId").is(qo.getDestId()));
        }
        //主题id
        if (StringUtils.hasLength(qo.getThemeId())){
            query.addCriteria(Criteria.where("themeId").is(qo.getThemeId()));
        }


        Pageable pageable = PageRequest.of(qo.getCurrentPage()-1, qo.getPageSize(), Sort.Direction.ASC, "_id");

        //调用工具方法,返回分页数据
        return PagingUtil.query(query, template, Strategy.class, pageable);

    }

    @Override
    public void changeState(int state, String id) {
        if (!StringUtils.hasLength(id)){
            throw new LogicalException("参数异常");
        }
        //查询该攻略
        Strategy strategy = this.get(id);
        //修改攻略状态
        strategy.setState(state);
        //更新
        this.update(strategy);

    }

    @Override
    public void updateStatisVO(StrategyStatisVO vo) {

        Query query = new Query();
        //拼接条件
        query.addCriteria(Criteria.where("_id").is(vo.getStrategyId()));
        //更新类
        Update update = new Update();
        update.set("viewnum", vo.getViewnum());
        update.set("replynum", vo.getReplynum());
        update.set("favornum", vo.getFavornum());
        update.set("sharenum", vo.getSharenum());
        update.set("thumbsupnum", vo.getThumbsupnum());
        //将所有vo数据都存到数据库
        template.updateMulti(query, update, Strategy.class);

    }

}
